package txt2bmp;

/*
 * 弄个音频版的
 * 判断是否以bmp结尾
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import javax.swing.JOptionPane;

public class Txt2Bmp {
	private File bmp;
	private File txt;
	private int txtShaoDeZiJie;

	public Txt2Bmp(File bmp, File txt) {
		this.bmp = bmp;
		this.txt = txt;
	}

	private byte[] getBmp() throws IOException {
		//在源文件的包中使用
		 String packagePath=Txt2Bmp.class.getResource("").getPath();
		//文件路径中有中文
		 String path=URLDecoder.decode(packagePath,System.getProperty("file.encoding"));
		 FileInputStream in = new FileInputStream(path+"bmp.bmp");

		//在class文件包中使用
//		InputStream in = Txt2Bmp.class.getResourceAsStream("/txt2bmp/bmp.bmp");
		byte[] bmp = new byte[54];
		in.read(bmp);
		in.close();
		return bmp;
	}

	private byte[] setBmp() throws IOException {
		byte[] bmp = getBmp();
		// 在图象里三个字节表示一个像素颜色
		long size = txt.length() / 3 + 1;
		int width = (int) Math.sqrt(size);
		int count = 0;
		for (int i = 18; i <= 21; i++) {
			bmp[i] = (byte) ((width >>> count * 8) & 0xff);
			count++;
		}
		int height = width + 1;
		count = 0;
		for (int i = 22; i <= 25; i++) {
			bmp[i] = (byte) ((height >>> count * 8) & 0xff);
			count++;
		}
		long bmpSize=0;
		for(int i=0;i<3;i++){
			if((width*3+i)%4==0){
				bmpSize=(width*3+i)*height+54;
				break;
			}
		}
		count=0;
		for (int i = 2; i <= 5; i++) {
			bmp[i] = (byte) ((bmpSize >>> count * 8) & 0xff);
			count++;
		}
		long bmpDataSize=bmpSize-54;
		count=0;
		for(int i=34;i<=37;i++){
			bmp[i]=(byte) ((bmpDataSize >>> count * 8) & 0xff);
			count++;
		}
		txtShaoDeZiJie=(int) (bmpDataSize-txt.length());
		return bmp;
	}

	public void txt2bmp() throws IOException {
		byte[] b = setBmp();
		FileOutputStream out = new FileOutputStream(bmp);
		out.write(b);
		FileInputStream in = new FileInputStream(txt);
		byte[] buf = new byte[1024];
		int num;
		while ((num = in.read(buf)) != -1) {
			out.write(buf, 0, num);
			out.flush();
		}

    byte[] heantai="heantai".getBytes();
    byte[] txtShaodeZiJie=new byte[txtShaoDeZiJie];
    if(heantai.length<txtShaoDeZiJie){
            System.arraycopy(heantai, 0, txtShaodeZiJie, 0, heantai.length);
    }else{
        System.arraycopy(heantai, 0, txtShaodeZiJie, 0, txtShaoDeZiJie);
    }
		out.write(txtShaodeZiJie);
		out.flush();
		in.close();
		out.close();
		int option=JOptionPane.showConfirmDialog(null, "转换完成，是否打开文件夹？");
		if(option==JOptionPane.OK_OPTION){
			Runtime.getRuntime().exec("explorer.exe " + bmp.getParent());
		}
	}
}
